import React, { Component } from 'react';
import { Button, Input, Space, Switch, Modal, Form, Col, Row, Tag, Select, Upload, message } from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheDialog from '@/components/TheDialog'
import { apiPage, apiDisplay, apiDel, apiView, apiGetGoodsDetail, apiExportCutpriceOrder } from '@/request/marketingTool'
import { exportSheetTable } from '@/utils/exportTable.js'
import './style.scss'
import { UploadOutlined } from "@ant-design/icons";
import store from "@/store/store"
const { Search } = Input;
const { Option } = Select;
export default class Bargain extends Component {
    constructor() {
        super()
        this.state = {
            exportLoading: false,
            title: "",
            columns: [
                {
                    title: "商品名称",
                    dataIndex: "title",
                    key: "title",
                },
                {
                    title: "门店名称",
                    dataIndex: "storeName",
                    key: "storeName",
                },
                {
                    title: "规格",
                    dataIndex: "skuJson",
                    key: "skuJson",
                    render: (text, render) => {
                        return text ? JSON.parse(text).skuAttribute.map(item => `${item.key}:${item.value}`).join("，") : '';
                    },
                },
                {
                    title: "商品价格",
                    dataIndex: "price",
                    key: "price",
                    render: (text, render) => {
                        return (
                            <div>
                                原价: <React.$Price price={render.cutPrice} />
                                <br />
                                低价: <React.$Price price={render.cutPriceLow} />
                            </div>
                        )
                    },
                },
                {
                    title: "砍价有效期",
                    dataIndex: "activityName",
                    key: "activityName",
                    render: (text, render) => {
                        return `${render.startTime} 至 ${render.endTime}`;
                    },
                },
                {
                    title: "砍价库存",
                    dataIndex: "originStock",
                    key: "originStock", render: (text, render) => {
                        return text == -1 ? '不限制' : text;
                    },
                },
                {
                    title: "当前库存",
                    dataIndex: "stock",
                    key: "stock",
                    render: (text, render) => {
                        return text == -1 ? '不限制' : text;
                    },
                },
                {
                    title: "砍价人数",
                    dataIndex: "userNum",
                    key: "userNum",
                },
                // {
                //     title: "已下单人数",
                //     dataIndex: "activityName",
                //     key: "activityName",
                // },
                {
                    title: "创建日期",
                    dataIndex: "createTime",
                    key: "createTime",
                },
                {
                    title: "上架/下架",
                    dataIndex: "activityStatus",
                    key: "activityStatus",
                    render: (text, render) => {
                        return <Switch defaultChecked={text} onChange={(e) => this.display(e, render)} />;
                    },
                },
                {
                    title: "操作",
                    width: 200,
                    fixed: 'right',
                    render: (text, render) => {
                        return (
                            <div>
                                <TheButton haspermi={['marketingTool:bargain:view']} onClick={() => this.props.history.push('/marketingTool/bargainView/' + text.id)} >查看</TheButton>
                                <TheButton haspermi={['marketingTool:bargain:edit']} onClick={() => this.props.history.push('/marketingTool/bargainAdd/' + text.id)} >编辑</TheButton>
                                <TheButton haspermi={['marketingTool:bargain:delete']} onClick={() => this.del(text)}>删除</TheButton>
                            </div>
                        );
                    },
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10,
            },
            total: 0,
            isModalVisible: false,
            info: {},
            currentSku: {},
            productSku: {},
            activityStatus: "",
            activityType: "",
            isVisible: false,
            uploadLoading: false,
            fileList: [],
        }
    }
    componentDidMount() {
        let searchParams = store.getState().searchValue
        console.log(searchParams);
        let { pageNo, pageSize, title,pathName } = searchParams

        if (searchParams && pageNo && pathName == 'marketingTool') {
            this.setState({
                title: title,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                }
            }, () => {
                this.getData()
            })
        } else {
            this.getData()
        }
    }
    onView(row) {
        apiView({ id: row.id }).then(res => {
            if (res.code === 0) {

                this.setState({ isModalVisible: true, info: res.data })
                this.apiGetGoodsDetail(res.data.goodsId, res.data.dataId)
            }

        })

    }
    del(row) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                apiDel({ id: row.id }).then(res => {
                    if (res.code === 0) {
                        this.getData()
                        React.$message({
                            type: 'success',
                            content: res.codeMessage
                        })
                    } else {
                        React.$message({
                            type: 'warning',
                            content: res.codeMessage
                        })
                    }
                })
            }
        });

    }
    async apiGetGoodsDetail(goodsId, skuId) {
        let res = await apiGetGoodsDetail({ goodsId })
        if (res.code === 0) {
            if (skuId) {
                this.setState({
                    currentSku: res.data.skuInfo.filter(item => item.SKUId === skuId)[0],
                    productSku: res.data
                })
            }

        }
    }
    display(e, row) {
        apiDisplay({ id: row.id }).then(res => {
            if (res.code === 0) {
                row.activityStatus = !row.activityStatus
                React.$message({
                    type: 'success',
                    content: res.codeMessage
                })
            } else {
                React.$message({
                    type: 'warning',
                    content: res.codeMessage
                })
                this.getData()
            }
        })
    }

    getData() {
        let { pageData, title, activityStatus, activityType } = this.state
        let params = {
            type: activityType,
            activityStatus,
            title, ...pageData,
        }
        store.dispatch({
            type: 'SaveSearchValues',
            data: {
                pathName:"marketingTool",
                ...params
            }
        })
        this.setState({
            dataSource: []
        })
        apiPage({ ...params }).then(res => {
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount
                })
            }
        })
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => this.getData())
    }
    onSearch(e) {
        console.log(e);
        this.setState({
            title: e,
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
        }, () => this.getData())

    }
    handleCancel() {
        this.setState({
            isModalVisible: false,
            productSku: {},
            currentSku: {},
            info: {}
        })
    }
    handleChange = (e) => {
        // console.log(e);
        this.setState({
            activityStatus: e,
            pageData: {
                pageNo: 1,
                pageSize: 10
            }
        }, () => {
            this.getData()
        })
    }
    typeChange = (e) => {
        this.setState({
            activityType: e,
            pageData: {
                pageNo: 1,
                pageSize: 10
            }
        }, () => {
            this.getData()
        })
    }
    exportList() {
        apiExportCutpriceOrder().then(res => {
            if (res.code === 0) {
                let tH_data = [
                    { prop: "orderCode", title: '订单号' },
                    { prop: "memberId", title: '用户ID' },
                    { prop: "title", title: '商品名称' },
                    { prop: "materialId", title: '物料id' },
                    { prop: "skuCurrentPrice", title: '商品现价', valueType: 'number' },
                    { prop: "count", title: '帮砍人数', valueType: 'number' },
                    { prop: "payState", title: '订单状态' },
                    { prop: "payTime", title: '支付时间' },
                    { prop: "orderPayPrice", title: '支付金额', valueType: 'number' }
                ],
                    tB_data = res.data.map(item => {
                        return {
                            orderCode: item.orderCode,
                            memberId: item.memberId,
                            title: item.title,
                            materialId: item.materialId,
                            skuCurrentPrice: Number(item.skuCurrentPrice / 100).toFixed(2),
                            count: item.count,
                            payState: item.payState == 1 ? '未支付' : item.payState == 2 ? '支付完成' : '支付失败',
                            payTime: item.payTime,
                            orderPayPrice: Number(item.orderPayPrice / 100).toFixed(2),
                        }
                    })
                const option = { fileName: '限时砍价', tH_data, tB_data, isSheet: true, merge: false }
                exportSheetTable(option)
            }
        })
    }
    onDownLoad = () => {
        const eleLink = document.createElement('a');
        eleLink.style.display = 'none';
        // eleLink.target = "_blank"
        eleLink.href = 'https://hqmimage.oss-cn-beijing.aliyuncs.com/%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls';
        // eleLink.download = url;
        // eleLink.href = record;
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
    }
    onUpload = () => {
        this.setState({
            isVisible: true
        })
    }
    closeDialog = () => {
        this.setState({
            isVisible: false
        })
    }
    onFinish = () => {
        let { fileList } = this.state
        let formData = new FormData();
        fileList.forEach((file) => {
            formData.append('file', file);
        });
        this.setState({ uploadLoading: true }); // You can use any AJAX library you like

        fetch(React.$BaseUrl + '/admin/marketingCutprice/excelImport', {
            method: "post",
            headers: {
                RSnetToken: sessionStorage.getItem('RSnetToken')
            },
            body: formData,
        })
            .then((res) => {
                res.json().then(res => {
                    if (res.code === 0) {
                        this.setState({ fileList: [] })
                        message.success('添加成功')
                        this.setState({ uploadLoading: false });
                        this.closeDialog()
                        this.getData()
                    } else {
                        message.error(res.codeMessage)
                    }
                })
            })
            .catch((res) => {
                console.log(res);
                message.error('上传失败.');
            })
            .finally(() => {
                this.setState({ uploadLoading: false });
            });
    }
    render() {
        const { columns, dataSource, fileList, isVisible, pageData, exportLoading, total, info, isModalVisible, currentSku, productSku, uploadLoading, activityStatus, activityType } = this.state
        let filedata = {
            accept: ".xls,.xlsx,application/vnd.ms-excel",
            maxCount: 1,
            onRemove: (file) => {
                const index = fileList.indexOf(file);
                const newFileList = fileList.slice();
                newFileList.splice(index, 1);
                this.setState({
                    fileList: newFileList
                })
            },
            beforeUpload: (file) => {
                this.setState({
                    fileList: [file]
                })
                return false;
            },
            fileList,
        };
        return (
            <div className="p-layout-box">
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                    <Space direction="vertical">
                        <Search
                            placeholder="关键字"
                            onSearch={(e) => this.onSearch(e)}
                            style={{
                                width: 200,
                            }}
                        />
                    </Space>
                    &nbsp;&nbsp;
                    <Select
                        defaultValue={activityStatus}
                        style={{
                            width: 120,
                        }}
                        onChange={(e) => this.handleChange(e)}
                    >
                        <Option value="" >
                            全部
                        </Option>
                        <Option value="1" >
                            上架
                        </Option>
                        <Option value="0" >
                            下架
                        </Option>
                    </Select>
                    &nbsp;&nbsp;
                    <Select
                        defaultValue={activityType}
                        style={{
                            width: 120,
                        }}
                        onChange={(e) => this.typeChange(e)}
                    >
                        <Option value="" >
                            全部
                        </Option>
                        <Option value="0" >
                            一元
                        </Option>
                        <Option value="1" >
                            底价
                        </Option>
                    </Select>
                    &nbsp;&nbsp;
                    <TheButton size="middle" type="primary" haspermi={['marketingTool:bargain:add']} onClick={() => this.props.history.push('/marketingTool/bargainAdd/' + null)}>+ 新建</TheButton>
                    &nbsp;&nbsp;
                    <TheButton size="middle" type="default" loading={exportLoading} haspermi={['marketingTool:bargain:exportList']} onClick={this.exportList}>限时砍价导出</TheButton>
                    &nbsp;&nbsp;
                    <TheButton size="middle" type="default" loading={exportLoading} haspermi={['marketingTool:bargain:downLoad']} onClick={this.onDownLoad}>下载模板</TheButton>
                    &nbsp;&nbsp;
                    <TheButton size="middle" type="default" loading={exportLoading} haspermi={['marketingTool:bargain:upload']} onClick={this.onUpload}>批量上传</TheButton>
                </div>
                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={columns}
                    dataSource={dataSource}
                />
                <ThePagination pageNo={pageData.pageNo} pageSize={pageData.pageSize} total={total} pageChange={this.pageChange} />
                <Modal title="查看详情" visible={isModalVisible} width="60%" onCancel={() => this.handleCancel()} footer={null}>
                    <Form
                        labelCol={{
                            span: 8,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                    >
                        <Row>

                            {
                                productSku.hasOwnProperty('skuInfo') &&
                                <Col span={12} >
                                    <Form.Item
                                        label="商品"
                                        name="cutMode"

                                    >
                                        <div className='goodsDesc'>
                                            <div className='info'>
                                                <img src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''} alt="商品图片" className='goodsImg' />
                                                <div className="goodsInfo">
                                                    <p className='name'>{info.title}</p>
                                                    <p className='price' >
                                                        价格:&nbsp;&nbsp;<React.$Price price={currentSku.skuCurrentPrice} />&nbsp;&nbsp;
                                                        <React.$Price price={currentSku.skuOriginalPrice} del={true} />
                                                    </p>
                                                </div>
                                            </div>
                                            <div className='goodsSku'>
                                                {
                                                    productSku.skuInfo.map(item =>
                                                        <Tag className='tag' key={item.SKUId} color={item.SKUId === currentSku.SKUId ? "cyan" : ''} >
                                                            {item.skuAttribute.map(item2 => item2.value).join(',')}
                                                        </Tag>
                                                    )
                                                }

                                            </div>
                                        </div>
                                    </Form.Item>
                                </Col>
                            }
                            <Col span={12}>
                                <Form.Item
                                    label="砍价模式"
                                    name="cutMode"

                                >
                                    <div>{info.cutMode === 0 ? '无需砍到底价即可购买' : '砍到底价才可购买'}</div>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="砍价最低价"
                                    name="cutPriceLow"

                                >
                                    <React.$Price price={info.cutPriceLow} />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="活动时间"
                                    name="activityTime"

                                >
                                    <div>{info.startTime} 至 {info.endTime}</div>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="砍价有效期"
                                    name="expire"

                                >
                                    <div>{info.expire}小时</div>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="砍价库存"
                                    name="originStock"

                                >
                                    <div>{info.originStock === -1 ? '不限制' : info.originStock}</div>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="帮砍价格"
                                    name="cutPriceType"

                                >
                                    <div>{info.cutPriceType === 0 ? '随机金额' : '固定金额'}</div>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="帮砍人数"
                                    name="userNum"

                                >
                                    <div>{info.userNum}</div>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="每人限购"
                                    name="userBuyLimit"
                                >
                                    <div>{info.userBuyLimit === -1 ? '不限制' : info.userBuyLimit}</div>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="新人一刀抵多刀"
                                    name="newCutCount"
                                >
                                    <div>{info.newCutCount}</div>
                                </Form.Item>
                            </Col>
                        </Row>

                    </Form>
                </Modal>
                <TheDialog
                    width={400}
                    title={'批量上传'}
                    visible={isVisible}
                    handleCancel={this.closeDialog}
                    footer={null}
                >
                    <Form onFinish={this.onFinish}>
                        <Form.Item label='上传文件' rules={[{ required: true }]} name="upFiles">
                            <Upload {...filedata} >
                                <Button icon={<UploadOutlined />}>选择文件</Button>
                            </Upload>
                        </Form.Item>
                        <Form.Item>
                            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                                <Space>
                                    <Button onClick={this.closeDialog}>取消</Button>
                                    <Button loading={uploadLoading} type="primary" htmlType="submit">确认</Button>
                                </Space>
                            </div>
                        </Form.Item>
                    </Form>
                </TheDialog>
            </div>
        );
    }
}
